package com.netease.financial.module.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.netease.financial.R;
import com.netease.financial.base.update.AppUpdateDialog;
import com.netease.financial.common.geography.Location;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.ImageUtil;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.PackageUtils;
import com.netease.financial.common.util.preferences.BadgePreferencesHelper;
import com.netease.financial.internal.di.HasComponent;
import com.netease.financial.internal.di.components.DaggerMainComponent;
import com.netease.financial.internal.di.components.MainComponent;
import com.netease.financial.internal.di.modules.MainModule;
import com.netease.financial.module.account.AccountFragment;
import com.netease.financial.module.activitypage.AdvertisementPreferencesHelper;
import com.netease.financial.module.asset.AssetFragment;
import com.netease.financial.module.home.HomeFragment;
import com.netease.financial.module.information.InformationFragment;
import com.netease.financial.module.product.ProductFragment;
import com.netease.financial.module.web.AccessToken;
import com.netease.financial.module.web.WebViewTabFragment;
import com.netease.financial.ui.activity.BaseAppCompatActivity;
import com.netease.financial.ui.fragment.BaseFragment;
import com.netease.financial.ui.fragment.TabFragment;
import com.netease.financial.ui.widget.FragmentTabHost;
import com.netease.financial.viewmodel.AppUpdateViewModel;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.badgeview.BGABadgeTextView;

public class MainActivity extends BaseAppCompatActivity
        implements WebViewTabFragment.OnFragmentInteractionListener, MainView, HasComponent<MainComponent> {

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String INTENT_EXTRA_KEY_TAB_POSITION = "tab_position";
    public static final String INTENT_EXTRA_KEY_LOGIN_WITH_ANOTHER_ACCOUNT = "login_with_another_account";
    private static final String DEVICE_PLATFORM = "android";

    private static final TabItem[] TAB_GROUP;

    public static MainActivity _self;

    static {
        TAB_GROUP = new TabItem[4];
        TAB_GROUP[0] = new TabItem("Home", R.string.description_tab_home, R.drawable.ic_tab_home, HomeFragment.class);
        TAB_GROUP[1] = new TabItem("Product", R.string.description_tab_product, R.drawable.ic_tab_product, ProductFragment.class);
//        TAB_GROUP[2] = new TabItem("Asset", R.string.description_tab_asset, R.drawable.ic_tab_asset, AssetFragment.class);
        TAB_GROUP[2] = new TabItem("Information", R.string.description_tab_information, R.drawable.ic_tab_information, InformationFragment.class);
        TAB_GROUP[3] = new TabItem("Account", R.string.description_tab_account, R.drawable.ic_tab_account, AccountFragment.class);
    }

    public static final int TAB_POSITION_HOME = 0;
    public static final int TAB_POSITION_PRODUCT = 1;
    //    public static final int TAB_POSITION_ACTIVITY_PAGE = 2;
    public static final int TAB_POSITION_ACCOUNT = 4;
    public static final int TAB_POSITION_INFORMATION = 3;
    public static final int TAB_POSITION_ASSET = 2;

    private LayoutInflater mInflater;
    private TextView mLeftNavigationItem;
    //    private ImageButton mRightNavigationItem;
    private TextView mTitleItem;
    private ImageView mActivityPageTabView;

    private static final long DOUBLE_CLICK_INTERVAL_MILLIS = 2000L;
    private boolean mRecentlyBackPressed = false;
    private Handler mExitHandler = new Handler();
    private Toast mExitToast;

    private boolean isLoginWithAnotherAccount = false;

    private int mTabHostPosition = TAB_POSITION_HOME;

    private MainComponent mainComponent;

    private Location locationService;
    private BDLocationListener myListener = new MyLocationListener();


    @Inject
    MainPresenter mainPresenter;

    @Bind(android.R.id.tabhost)
    FragmentTabHost mTabHost;

    @Bind(R.id.btn_share)
    ImageButton btnShare;

    public static Intent getCallingIntent(Context context) {
        Intent callingIntent = new Intent(context, MainActivity.class);
        callingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return callingIntent;
    }

    public static Intent getCallingIntent(Context context, int tabPosition) {
        Intent callingIntent = getCallingIntent(context);
        callingIntent.putExtra(INTENT_EXTRA_KEY_TAB_POSITION, tabPosition);
        return callingIntent;
    }

    public static Intent getLoginWithAnotherAccountCallingIntent(Context context) {
        Intent callingIntent = getCallingIntent(context, TAB_POSITION_ASSET);
        callingIntent.putExtra(INTENT_EXTRA_KEY_LOGIN_WITH_ANOTHER_ACCOUNT, true); // tell page to clear user data
        return callingIntent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationService = new Location(getApplicationContext());
        locationService.registerListener(myListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();
        _self = this;
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initializeInjector();
        initialize();
        handleIntent(getIntent());
    }

    private void initializeInjector() {
        this.mainComponent = DaggerMainComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule())
                .mainModule(new MainModule(new AccessToken(), DEVICE_PLATFORM, PackageUtils.getCurrentApkVersionCode(this), SecurityJNI.getAppSecret()))
                .build();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
        dispatchNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.mainPresenter.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.mainPresenter.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.mainPresenter.onDestroy();
        ButterKnife.unbind(this);
//        clearWebViewCache();
    }

    private void clearWebViewCache() {
        BadgePreferencesHelper.setUnreadPrivateMessageCount(0);
        if (mTabHost != null) {
            for (int i = 0; i < mTabHost.getTabWidget().getTabCount(); i++) {
                WebViewTabFragment webViewTabFragment = (WebViewTabFragment) mTabHost.getFragmentAtIndex(i);
                webViewTabFragment.clearWebViewCache();
            }
        }
    }

    private void initialize() {
        this.mainComponent.inject(this);

        initViews();
        initActionBar();
        initDebugConfig();
        initPresenter();
    }

    private void initPresenter() {
        this.mainPresenter.setView(this);
        this.mainPresenter.initialize();
        if (isLoginWithAnotherAccount) {
            this.mainPresenter.logout();
        } else {
            this.mainPresenter.updateActivityPage();
            this.mainPresenter.checkAppUpdate();
        }
    }

    private void initDebugConfig() {
        if (NfsLog.DEBUG_MODE) {
            if (mTitleItem == null) {
                return;
            }
            mTitleItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    DialogUtil.showDebugDialog(MainActivity.this);
                    getNavigator().navigateToLoginScreen(MainActivity.this, 1000);
                }
            });
        }
    }

    private void handleIntent(Intent intent) {
        if (intent.hasExtra(INTENT_EXTRA_KEY_TAB_POSITION)) {
            mTabHostPosition = intent.getIntExtra(INTENT_EXTRA_KEY_TAB_POSITION, TAB_POSITION_HOME);
            mTabHost.setCurrentTab(mTabHostPosition);
            isLoginWithAnotherAccount = intent.getBooleanExtra(INTENT_EXTRA_KEY_LOGIN_WITH_ANOTHER_ACCOUNT, false);

            NfsLog.d(TAG, "MainActivity.isLoginWithAnotherAccount:" + isLoginWithAnotherAccount);

            NfsLog.printStackTraceString("handleIntent.mTabHostPosition = " + mTabHostPosition);
        }
    }

    private void initViews() {
        mInflater = LayoutInflater.from(this);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        for (int i = 0; i < TAB_GROUP.length; i++) {
            TabItem tabItem = TAB_GROUP[i];
            addTab(tabItem.tag, tabItem.labelId, tabItem.iconId, tabItem.fragment);
            if (i == 1) {
//                addActivityPageIconView();
//            attachBadgeViewToFragmentAtIndex(i);
                setCustomTabItemView(2, R.drawable.ic_tab_dashboard_normal);
            }

            if (i <= 1) {
                attachBadgeViewToFragmentAtIndex(i);
            } else {
                attachBadgeViewToFragmentAtIndex(i + 1);
            }
        }

        mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        mTabHost.setCurrentTab(mTabHostPosition);
//        setCustomTabItemView(2, R.drawable.ic_tab_account_normal);
    }

    private void addActivityPageIconView() {
        mActivityPageTabView = getActivityPageIconView();
        TabHost.TabSpec tabSpec = mTabHost.newTabSpec("activity_page");
        tabSpec.setIndicator(mActivityPageTabView);
        mTabHost.addTab(tabSpec, Fragment.class, null);
        mActivityPageTabView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNavigator().navigateToActivityPage(MainActivity.this,
                        AdvertisementPreferencesHelper.getActivityPageTitle(),
                        AdvertisementPreferencesHelper.getActivityPageUrl());
            }
        });
    }

    private void addTab(String tag, @StringRes int stringResId, @DrawableRes int drawableResId, Class<?> fragment) {
        TabHost.TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(getTabItemView(stringResId, drawableResId));
        mTabHost.addTab(tabSpec, fragment, null);
    }

    private ImageView getActivityPageIconView() {
        ImageView iconView = new ImageView(this);
        ImageUtil.displayImage(iconView, AdvertisementPreferencesHelper.getActivityIconUrl(), R.drawable.ic_footer_tab_activity_default);

        return iconView;
    }

    /*
     * 由change事件调用的动态改变Tabhost图标的方法。
     */
    public void setCustomTabItemView(int tabIndex, @DrawableRes int drawableResId) {
        View view = mTabHost.getTabWidget().getChildAt(tabIndex);
        if (view == null && mTabHost.getTabHostCount() > 1) {
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec("Asset");
            ImageView imageview = new ImageView(this);
            imageview.setImageResource(drawableResId);
            tabSpec.setIndicator(imageview);
            mTabHost.addTab(tabSpec, AssetFragment.class, null);
            return;
        }

        if (view instanceof ImageView) {
            ((ImageView) view).setImageResource(drawableResId);
        }
//        RelativeLayout rootView = (RelativeLayout) view;
//        rootView.setImageResource(drawableResId);
////        rootView.setPadding(0, 0, 0, 0);
//        rootView.setBackgroundColor(Color.BLACK);
//        View childView = rootView.getChildAt(0);
//        if (childView instanceof BGABadgeTextView) {
//            rootView.removeAllViews();
//        }
//
//        ImageView imageview = new ImageView(this);
//        imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
//        Drawable drawable = imageview.getResources().getDrawable(drawableResId);
//        imageview.setImageDrawable(drawable);
//        imageview.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
//        imageview.setPadding(0, 0, 0, 0);
//        rootView.addView(imageview);

    }

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    private View getTabItemView(@StringRes int stringResId, @DrawableRes int drawableResId) {
        View view = mInflater.inflate(R.layout.tab_item, null, false);
        Drawable drawable = getResources().getDrawable(drawableResId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        }
        BGABadgeTextView badgeView = ButterKnife.findById(view, R.id.tab_description);
        badgeView.setText(stringResId);
        badgeView.setCompoundDrawables(null, drawable, null, null);
        return view;
    }

    private void attachBadgeViewToFragmentAtIndex(int index) {
        View view = mTabHost.getTabWidget().getChildTabViewAt(index);
        BGABadgeTextView badgeView = ButterKnife.findById(view, R.id.tab_description);

        TabFragment tabFragment = (TabFragment) mTabHost.getFragmentAtIndex(index);
        tabFragment.setTabBadgeView(badgeView);
    }

    private void initActionBar() {
        if (getSupportActionBar() == null) {
            return;
        }
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.this.dispatchCustomViewItemSelected(v);
            }
        };

        mLeftNavigationItem = getLeftNavigationItem();
        mLeftNavigationItem.setOnClickListener(listener);

        mTitleItem = getTitleItem();
        mTitleItem.setOnClickListener(listener);

//        mRightNavigationItem = getRightNavigationItem();
        btnShare.setOnClickListener(listener);
        btnShare.setVisibility(View.INVISIBLE);
    }

    private void dispatchCustomViewItemSelected(View view) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(mTabHost.getCurrentTabTag());
        ((BaseFragment) fragment).performCustomViewItemSelected(view);
    }

    private void dispatchNewIntent(Intent intent) {
        int count = mTabHost.getTabWidget().getTabCount();
        for (int i = 0; i < count; i++) {
            Fragment fragment = mTabHost.getFragmentAtIndex(i);
            if (fragment != null && fragment instanceof BaseFragment) {
                ((BaseFragment) fragment).onNewIntent(intent);
            }
        }
    }

    private static final class TabItem {
        String tag;
        int labelId;
        int iconId;
        Class<?> fragment;

        public TabItem(String tag, int labelId, int iconId, Class<?> fragment) {
            this.tag = tag;
            this.labelId = labelId;
            this.iconId = iconId;
            this.fragment = fragment;
        }
    }

    private Runnable mExitRunnable = new Runnable() {
        @Override
        public void run() {
            mRecentlyBackPressed = false;
        }
    };

    @Override
    public void onBackPressed() {
        //You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
        if (mRecentlyBackPressed) {
            if (mExitToast != null) {
                mExitToast.cancel();
            }
            mExitHandler.removeCallbacks(mExitRunnable);
            super.onBackPressed();
            return;
        }
        mRecentlyBackPressed = true;
        mExitToast = Toast.makeText(this, R.string.exit_app_prompt, Toast.LENGTH_SHORT);
        mExitToast.show();
        mExitHandler.postDelayed(mExitRunnable, DOUBLE_CLICK_INTERVAL_MILLIS);
    }

    @Override
    public void setNavigationTitle(final String title) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setTitle(title);
            }
        });
    }

    @Override
    public void showBottomTabWidget(final boolean show) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final int visibility = show ? View.VISIBLE : View.GONE;
                mTabHost.getTabWidget().setVisibility(visibility);

                // 在某些机型上，比如一加手机，隐藏tab widget的同时，必须同时隐藏tab widget中包含的tab，
                // 否则tab会将focus抢走，导致输入法无法正常输入
                int count = mTabHost.getTabWidget().getTabCount();
                for (int i = 0; i < count; i++) {
                    mTabHost.getTabWidget().getChildTabViewAt(i).setVisibility(visibility);
                }
                int inputMode = show ? WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN :
                        (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                getWindow().setSoftInputMode(inputMode);
            }
        });
    }

    @Override
    public void hideNavBackItem() {
        if (mLeftNavigationItem == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLeftNavigationItem.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    public void showNavBackItem() {
        if (mLeftNavigationItem == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLeftNavigationItem.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void hideOptionMenu() {
        if (btnShare == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnShare.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    public void showOptionMenu() {
        if (btnShare == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnShare.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void showAppUpdateView(AppUpdateViewModel viewModel) {
        refreshAssetBadgeView();
        showAppUpdateDialog(viewModel);
    }

    @Override
    public void showLoginView() {
        setCurrentTab(TAB_POSITION_ASSET);
    }

    @Override
    public void changeActivityPageIcon(String iconUrl) {
        ImageUtil.displayImage(mActivityPageTabView, iconUrl, R.drawable.ic_footer_tab_activity_default);
    }

    /**
     * Show dialog
     */
    private void showAppUpdateDialog(AppUpdateViewModel viewModel) {
        AppUpdateDialog dialog = new AppUpdateDialog();
        dialog.setUpdateDetail(viewModel);
        dialog.show(getSupportFragmentManager(), null);
    }

    @Override
    public Context getContext() {
        return this;
    }

    private void refreshAssetBadgeView() {
        if (mTabHost != null) {
            TabFragment assetFragment = (TabFragment) mTabHost.getFragmentAtIndex(TAB_POSITION_ASSET);
            assetFragment.refreshTabBadgeView();
        }
    }

    @Override
    public void setCurrentTab(int position) {
        mTabHost.setCurrentTab(position);
    }

    @Override
    public MainComponent getComponent() {
        return this.mainComponent;
    }

    //位置信息服务的监听器
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("{");
//            sb.append("time : ");
//            sb.append(location.getTime());
//            sb.append("\nerror code : ");
//            sb.append(location.getLocType());
//            sb.append("\nlatitude : ");
//            sb.append(location.getLatitude());
//            sb.append("\nlontitude : ");
//            sb.append(location.getLongitude());
//            sb.append("\nradius : ");
//            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                sb.append("\nspeed : ");
//                sb.append(location.getSpeed());// 单位：公里每小时
//                sb.append("\nsatellite : ");
//                sb.append(location.getSatelliteNumber());
//                sb.append("\nheight : ");
//                sb.append(location.getAltitude());// 单位：米
//                sb.append("\ndirection : ");
//                sb.append(location.getDirection());// 单位度
                sb.append("address:\"");
                sb.append(location.getAddrStr());
                sb.append("\"");
                sb.append(",");
                sb.append("province:\"");
                sb.append(location.getProvince());
                sb.append("\"");
                sb.append(",");
                sb.append("city:\"");
                sb.append(location.getCity());
                sb.append("\"");
//                sb.append("\ndescribe : ");
//                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("address:\"");
                sb.append(location.getAddrStr());
                sb.append("\"");
                sb.append(",");
                sb.append("province:\"");
                sb.append(location.getProvince());
                sb.append("\"");
                sb.append(",");
                sb.append("city:\"");
                sb.append(location.getCity());
                sb.append("\"");
                //运营商信息
//                sb.append("\noperationers : ");
//                sb.append(location.getOperators());
//                sb.append("\ndescribe : ");
//                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                sb.append("\ndescribe : ");
//                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
//                sb.append("\ndescribe : ");
//                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                sb.append("\ndescribe : ");
//                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                sb.append("\ndescribe : ");
//                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
//            sb.append("Describe : \"");
//            sb.append(location.getLocationDescribe());// 位置语义化信息
//            sb.append("\"");
            sb.append("}");
            if (sb.toString().length() > 3) {
                SharedPreferences locationSharedPreferences = getSharedPreferences("GEOGRAPHY_LOCATION", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = locationSharedPreferences.edit();
                editor.putString("SHAREPREFER_LOCATION", sb.toString());
                editor.commit();
                locationService.stop();
            }
//            List<Poi> list = location.getPoiList();// POI数据
//            if (list != null) {
//                sb.append("\npoilist size = : ");
//                sb.append(list.size());
//                for (Poi p : list) {
//                    sb.append("\npoi= : ");
//                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
//                }
//            }
            Log.i("BaiduLocation", sb.toString());
        }

    }

}
